package com.athuahua.controller;

import com.athuahua.service.AsyncService;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author: huahua
 * @Date: 2024/8/17 0017
 * @Time: 6:40
 * @Description:
 */
@RestController
@Slf4j
public class AsyncController {

    @Resource
    private AsyncService asyncService;

    @GetMapping("sendMails")
    @SneakyThrows
    public String sendMails() {
        String[] emails = {
                "email1@gmail.com",
                "email2@gmail.com",
                "email3@gmail.com",
                "email4@gmail.com",
                "email5@gmail.com"
        };
        for (int i = 0; i < emails.length; i++) {
            asyncService.sendMail(emails[i], "Hello, this is a test mail");
        }
        return "success";
    }


    @GetMapping("blockSendMails")
    @SneakyThrows
    public String blockSendMails() {
        CompletableFuture<String>[] futures = new CompletableFuture[5];

        String[] emails = {
                "email1@gmail.com",
                "email2@gmail.com",
                "email3@gmail.com",
                "email4@gmail.com",
                "email5@gmail.com"
        };
        for (int i = 0; i < emails.length; i++) {
            futures[i] = asyncService.blockSendMail(emails[i], "Hello, this is a test mail");
        }
        //阻塞等待所有任务完成响应结果
        CompletableFuture.allOf(futures);

        StringBuffer output = new StringBuffer();
        for (int i = 0; i < emails.length; i++) {
            try {
                output.append(futures[i].get() + "\n");
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        }

        return output.toString();
    }
}
